<template>
  <div class="chart-container" ref="chartContainer">
    <div class="chart" ref="chart"></div>
    <div class="list-panel">
      <h3 class="list-title">各省设备数量统计</h3>
      <div class="list-header">
        <span class="header-rank">排名</span>
        <span class="header-province">省份</span>
        <span class="header-count">设备数量</span>
        <span class="header-percent">占比</span>
      </div>
      <div class="list-content">
        <div
            v-for="(item, index) in sortedProvinces"
            :key="item.name"
            class="list-item"
            :class="{
            'highlight': highlightProvince === item.name
          }"
            @mouseenter="handleProvinceHover(item.name)"
            @mouseleave="handleProvinceLeave"
        >
          <span class="item-rank" :class="{
            'rank-1': index === 0,
            'rank-2': index === 1,
            'rank-3': index === 2,
            'rank-4': index === 3,
            'rank-5': index === 4
          }">{{ index + 1 }}</span>
          <span class="item-province">{{ item.name  }}</span>
          <span class="item-count">{{ item.value  }}台</span>
          <span class="item-percent">{{ ((item.value  / totalValue) * 100).toFixed(2) }}%</span>
          <div class="progress-bar" :style="{ width: `${(item.value  / maxValue) * 100}%` }"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { onMounted, ref, onUnmounted, computed, watch } from 'vue'
import chinaJson from '~/assets/china.json'

export default {
  name: 'DeviceChinaMap',
  props: {
    data: Array,
    title: String
  },
  setup(props) {
    const chartContainer = ref(null)
    const chart = ref(null)
    const highlightProvince = ref(null)
    let myChart = null
    let animationInterval = null

    const sortedProvinces = computed(() => {
      return [...props.data].sort((a,  b) => b.value  - a.value)
    })

    const maxValue = computed(() => {
      return Math.max(...props.data.map(item  => item.value),  1)
    })

    const totalValue = computed(() => {
      return props.data.reduce((sum,  item) => sum + item.value,  0)
    })

    const processMapData = () => {
      return props.data.map(item  => {
        return {
          ...item,
          itemStyle: {
            areaColor: '#0c3653',
            borderColor: '#1a5b7e',
            borderWidth: 1,
            shadowColor: 'rgba(79, 216, 222, 0.5)',
            shadowBlur: 10
          },
          emphasis: {
            itemStyle: {
              areaColor: '#4fd8de',
              borderColor: '#fff',
              borderWidth: 1.5,
              shadowColor: 'rgba(79, 216, 222, 0.8)',
              shadowBlur: 20
            }
          }
        }
      })
    }

    const handleProvinceHover = (provinceName) => {
      highlightProvince.value  = provinceName
      if (myChart) {
        myChart.dispatchAction({
          type: 'highlight',
          name: provinceName
        })
        // 添加闪烁动画
        startBlinkAnimation(provinceName)
      }
    }

    const handleProvinceLeave = () => {
      highlightProvince.value  = null
      if (myChart) {
        myChart.dispatchAction({
          type: 'downplay',
          name: highlightProvince.value
        })
        // 停止闪烁动画
        stopBlinkAnimation()
      }
    }

    const startBlinkAnimation = (provinceName) => {
      stopBlinkAnimation()
      let blinkCount = 0
      const maxBlinks = 3

      animationInterval = setInterval(() => {
        if (blinkCount >= maxBlinks * 2) {
          clearInterval(animationInterval)
          return
        }

        myChart.dispatchAction({
          type: blinkCount % 2 === 0 ? 'highlight' : 'downplay',
          name: provinceName
        })

        blinkCount++
      }, 300)
    }

    const stopBlinkAnimation = () => {
      if (animationInterval) {
        clearInterval(animationInterval)
        animationInterval = null
      }
    }

    const initChart = () => {
      if (!chart.value)  return

      myChart = echarts.init(chart.value)

      const option = {
        title: {
          text: props.title,
          left: 'center',
          top: 10,
          textStyle: {
            color: '#fff',
            fontSize: 16,
            fontWeight: 'bold',
            textShadow: '0 0 10px rgba(79, 216, 222, 0.8)'
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: params => {
            const percent = ((params.value  / totalValue.value)  * 100).toFixed(2)
            return `<div style="font-weight:bold">${params.name}</div>
                    <div>设备数量: ${params.value} 台</div>
                    <div>占比: ${percent}%</div>`
          },
          backgroundColor: 'rgba(12, 54, 83, 0.9)',
          borderColor: '#4fd8de',
          borderWidth: 1,
          textStyle: {
            color: '#fff'
          },
          extraCssText: 'box-shadow: 0 0 10px rgba(79, 216, 222, 0.5);'
        },
        visualMap: {
          min: 0,
          max: maxValue.value,
          text: ['高', '低'],
          realtime: false,
          calculable: true,
          inRange: {
            color: ['#0c3653', '#1a5b7e', '#4fd8de']
          },
          textStyle: {
            color: '#fff'
          },
          // 添加动画效果
          hoverLink: true,
          animation: true,
          animationDuration: 1000,
          animationEasing: 'cubicInOut'
        },
        series: [{
          name: '设备分布',
          type: 'map',
          map: 'china',
          roam: true,
          zoom: 1.7,
          center: [105, 36],
          label: {
            show: false
          },
          emphasis: {
            label: {
              show: true,
              color: '#fff',
              fontSize: 12,
              fontWeight: 'bold',
              textShadow: '0 0 5px #000'
            }
          },
          data: processMapData(),
          // 添加地图动画
          animation: true,
          animationDuration: 1000,
          animationEasing: 'elasticOut',
          // 添加涟漪特效
          rippleEffect: {
            brushType: 'stroke',
            scale: 5,
            period: 4
          },
          // 添加区域呼吸动画
          itemStyle: {
            areaColor: '#0c3653',
            borderColor: '#1a5b7e',
            borderWidth: 1,
            shadowColor: 'rgba(79, 216, 222, 0.5)',
            shadowBlur: 10
          },
          // 添加数据流动画
          lines: getFlowLines(props.data),
          effect: {
            show: true,
            period: 4,
            trailLength: 0.2,
            symbol: 'arrow',
            symbolSize: 6,
            color: 'rgba(79, 216, 222, 0.8)'
          }
        }]
      }

      myChart.setOption(option)

      // 添加自动轮播高亮效果
      startAutoHighlight()

      window.addEventListener('resize',  handleResize)
    }

    // 生成数据流动线
    const getFlowLines = (data) => {
      const centerCoord = [105, 36] // 中国中心坐标
      const lines = []

      data.forEach(item  => {
        // 这里简化处理，实际应该根据省份坐标生成
        lines.push({
          coords: [centerCoord, getProvinceCenter(item.name)],
          lineStyle: {
            color: 'rgba(79, 216, 222, 0.5)',
            width: Math.min(3,  item.value  / maxValue.value  * 5),
            curveness: 0.2
          }
        })
      })

      return lines
    }

    // 模拟获取省份中心坐标
    const getProvinceCenter = (provinceName) => {
      // 实际项目中应该从geoJSON中获取精确坐标
      const mockCoords = {
        '北京': [116.4, 39.9],
        '上海': [121.47, 31.23],
        '广东': [113.23, 23.16],
        // 其他省份...
      }
      return mockCoords[provinceName] || [Math.random() * 40 + 80, Math.random()  * 20 + 20]
    }

    // 自动轮播高亮省份
    const startAutoHighlight = () => {
      if (!myChart || props.data.length  === 0) return

      let currentIndex = 0

      setInterval(() => {
        const province = sortedProvinces.value[currentIndex  % sortedProvinces.value.length].name
        myChart.dispatchAction({
          type: 'highlight',
          name: province
        })

        // 短暂显示后取消高亮
        setTimeout(() => {
          myChart.dispatchAction({
            type: 'downplay',
            name: province
          })
        }, 2000)

        currentIndex++
      }, 3000)
    }

    const handleResize = () => {
      myChart && myChart.resize()
    }

    onMounted(() => {
      echarts.registerMap('china',  chinaJson)
      initChart()
    })

    watch(() => props.data,  (newData) => {
      if (myChart) {
        // 添加数据更新动画
        myChart.setOption({
          series: [{
            data: processMapData(),
            lines: getFlowLines(newData)
          }],
          visualMap: {
            max: maxValue.value
          }
        }, {
          notMerge: true,
          lazyUpdate: true
        })
      }
    })

    onUnmounted(() => {
      window.removeEventListener('resize',  handleResize)
      myChart && myChart.dispose()
      stopBlinkAnimation()
    })

    return {
      chartContainer,
      chart,
      sortedProvinces,
      maxValue,
      totalValue,
      highlightProvince,
      handleProvinceHover,
      handleProvinceLeave
    }
  }
}
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  min-height: 600px;
  background: rgba(13, 42, 67, 0.3);
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.chart {
  width: 100%;
  height: 70%;
  background: rgba(13, 42, 67, 0.5);
  position: relative;
}

/* 添加地图容器的发光效果 */
.chart::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  border-radius: 8px;
  box-shadow: inset 0 0 30px rgba(79, 216, 222, 0.3);
  pointer-events: none;
  z-index: 1;
}

.list-panel {
  width: 100%;
  height: 30%;
  padding: 15px;
  background: rgba(13, 42, 67, 0.7);
  border-top: 1px solid rgba(79, 216, 222, 0.3);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.list-title {
  color: #4fd8de;
  margin: 0 0 15px 0;
  font-size: 16px;
  text-align: center;
  padding-bottom: 8px;
  border-bottom: 1px solid rgba(79, 216, 222, 0.3);
  position: relative;
  text-shadow: 0 0 8px rgba(79, 216, 222, 0.5);
}

.list-title::after {
  content: "";
  position: absolute;
  bottom: -1px;
  left: 25%;
  width: 50%;
  height: 2px;
  background: linear-gradient(90deg, transparent, #4fd8de, transparent);
  animation: titleGlow 2s infinite alternate;
}

@keyframes titleGlow {
  from {
    opacity: 0.5;
  }
  to {
    opacity: 1;
  }
}

.list-header {
  display: flex;
  padding: 8px 20px;
  background: rgba(11, 93, 232, 0.1);
  border-radius: 4px;
  margin-bottom: 8px;
  font-weight: bold;
  color: #4fd8de;
  font-size: 14px;
  text-shadow: 0 0 5px rgba(79, 216, 222, 0.3);
}

.header-rank {
  width: 50px;
  min-width: 50px;
}

.header-province {
  flex: 1;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.header-count {
  width: 80px;
  min-width: 80px;
  text-align: right;
}

.header-percent {
  width: 80px;
  min-width: 80px;
  text-align: center;
}

.list-content {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding-right: 4px;
}

/* 自定义滚动条样式 */
.list-content::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.list-content::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 3px;
}

.list-content::-webkit-scrollbar-thumb {
  background-color: rgba(79, 216, 222, 0.6);
  border-radius: 3px;
  transition: background-color 0.3s;
}

.list-content::-webkit-scrollbar-thumb:hover {
  background-color: rgba(79, 216, 222, 0.8);
}

.list-item {
  position: relative;
  padding: 12px 20px;
  display: flex;
  align-items: center;
  background: linear-gradient(90deg, rgba(11, 93, 232, 0.1), transparent);
  border-radius: 6px;
  margin-bottom: 8px;
  transition: all 0.3s ease;
  backdrop-filter: blur(2px);
  border: 1px solid rgba(79, 216, 222, 0.1);
  min-width: 0;
  animation: fadeIn 0.5s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.list-item:hover {
  background: linear-gradient(90deg, rgba(11, 93, 232, 0.2), transparent);
  transform: translateX(5px);
  box-shadow: 0 0 15px rgba(79, 216, 222, 0.3);
}

.highlight {
  background: linear-gradient(90deg, rgba(79, 216, 222, 0.2), transparent) !important;
  border-color: rgba(79, 216, 222, 0.5) !important;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(79, 216, 222, 0.4);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(79, 216, 222, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(79, 216, 222, 0);
  }
}

.item-rank {
  width: 50px;
  min-width: 50px;
  font-size: 14px;
  color: #fff;
  font-weight: bold;
  flex-shrink: 0;
}

.item-province {
  flex: 1;
  color: #fff;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding-right: 10px;
}

.item-count {
  width: 80px;
  text-align: right;
  color: #4fd8de;
  font-size: 14px;
  font-weight: bold;
  flex-shrink: 0;
  text-shadow: 0 0 5px rgba(79, 216, 222, 0.3);
}

.item-percent {
  width: 80px;
  text-align: right;
  color: #fff;
  font-size: 14px;
  flex-shrink: 0;
}

.progress-bar {
  position: absolute;
  bottom: 0;
  left: 70px;
  right: 180px;
  height: 3px;
  background: linear-gradient(90deg, rgba(11, 93, 232, 0.5), rgba(79, 216, 222, 0.8));
  border-radius: 2px;
  transition: all 0.6s ease;
  animation: progressGrow 1s ease-out;
}

@keyframes progressGrow {
  from {
    width: 0;
  }
}

/* 前五名排名数字颜色 */
.rank-1 {
  color: #ffd700 !important;
  text-shadow: 0 0 8px rgba(255, 215, 0, 0.5);
  animation: goldGlow 2s infinite alternate;
}

@keyframes goldGlow {
  from {
    text-shadow: 0 0 5px rgba(255, 215, 0, 0.5);
  }
  to {
    text-shadow: 0 0 15px rgba(255, 215, 0, 0.8);
  }
}

.rank-2 {
  color: #c0c0c0 !important;
  text-shadow: 0 0 5px rgba(192, 192, 192, 0.5);
}

.rank-3 {
  color: #cd7f32 !important;
  text-shadow: 0 0 5px rgba(205, 127, 50, 0.5);
}

.rank-4 {
  color: #4fd8de !important;
  text-shadow: 0 0 5px rgba(79, 216, 222, 0.5);
}

.rank-5 {
  color: #a1a1a1 !important;
  text-shadow: 0 0 5px rgba(161, 161, 161, 0.5);
}
</style>